package com.srx.user.service;

import com.srx.openfeign.feign.UserToElasticsearch;
import com.srx.openfeign.utils.EmailUtil;
import com.srx.openfeign.utils.PasswordUtil;
import com.srx.openfeign.utils.TokenUtil;
import com.srx.user.mapper.UserMapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 用户服务类
 * <p>提供用户相关的业务逻辑处理功能。包含用户登录、密码更新、信息查询等核心操作。通过整合Mapper层和Feign客户端实现数据持久化和远程调用。</p
 * @author 沈汝旭
 * @since 2025-10-18 10:54:05
 * @version 1.0
 */
@Service
public class UserService
{

    /**
	 * 用户Mapper接口
	 */
    private final UserMapper userMapper;
    /**
	 * Redis模板对象
	 */
	private final RedisTemplate<String, Object> redisTemplate;
    /**
	 * 用户与Elasticsearch服务之间的Feign接口
	 */
	private final UserToElasticsearch userToElasticsearch;
    /**
	 * RabbitMQ模板对象
	 */
	private final RabbitTemplate rabbitTemplate;


    /**
	 * 构造函数，注入Mapper接口和Redis模板对象
	 *
	 * @param userMapper 用户Mapper接口
	 * @param redisTemplate Redis模板对象
	 */
	@Autowired
	public UserService(UserMapper userMapper, RedisTemplate<String, Object> redisTemplate, UserToElasticsearch userToElasticsearch, RabbitTemplate rabbitTemplate)
	{
		this.userMapper = userMapper;
		this.userToElasticsearch = userToElasticsearch;
		this.rabbitTemplate = rabbitTemplate;
		this.redisTemplate = redisTemplate;
	}



	/**
	 * 用户登录
     * <p>用户登录功能，根据账号和密码进行验证，并返回token。</p>
	 *
	 * @param account 用户账号
	 * @param password 用户密码
	 * @return 登录成功返回token，登录失败返回null
	 */
	public String login(String account, String password)
	{
		//根据学号获取用户id
        Long id = userToElasticsearch.getUserIdByAccount(account);
		//存在此用户且密码正确
		if (id != 0 && PasswordUtil.verifyPassword(password, userMapper.getPasswordById(id)))
		{
			//生成token,有效期2小时
			HashMap<String, Object> claims = new HashMap<>(1);
			claims.put("userId", id);
			return TokenUtil.createToken("token令牌", claims, "2017142276@qq.com", new Date(System.currentTimeMillis()),
					new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 2));
		}
        return null;
	}


	/**
	 * 根据邮箱发送验证码
	 *
	 * @param email 用户输入的邮箱地址
	 * @return 验证码发送结果，true表示发送成功，false表示发送失败
	 */
    public Boolean sendEmail(String email)
    {
        //先验证邮箱合法性
        if (EmailUtil.isValidEmail(email))
        {
            //随机生成6位验证码
            Random random = new Random();
            String sixDigitNumber = String.valueOf(100000 + random.nextInt(900000));
            //发送包含验证码的邮件
            boolean result = EmailUtil.sendSimpleTextEmail("smtp.qq.com", 465, "2017142276@qq.com", EmailUtil.SMTP, "2017142276@qq.com", email, "紫槿云柚校园管理平台", "您的验证码为： " + sixDigitNumber + " ，15分钟内有效，请勿泄露给他人。若您没有使用紫槿云柚校园管理平台，请忽略本次邮件。");
            //如果发送成功，将验证码存入redis
            if (result)
            {
	            redisTemplate.opsForValue().set("email:"+email, sixDigitNumber, 15, TimeUnit.MINUTES);
            }
            return result;
        }
        return false;
    }


	/**
	 * 更新用户密码
	 *
	 * @param email 用户邮箱，用于查找用户和验证验证码
	 * @param code 验证码，用于验证用户身份
	 * @param password 新密码，用于替换旧密码
	 * @return 返回结果字符串，表明密码更新的结果
	 */
    public Boolean updatePassword(String email, String code, String password)
    {
        //获取redis中的验证码
        String redisCode = String.valueOf(redisTemplate.opsForValue().get("email:" + email));
        //验证码不对或过期
       if (redisCode == null || !redisCode.equals(code))
        {
	        return false;
        }
        else
        {
            //根据邮箱获取用户
            Long id = userToElasticsearch.getUserIdByEmail(email);
            //用户为空
            if (id == 0)
            {
	            return false;
            }
            else
            {
                //更新数据
	            return userMapper.updatePassword(id, PasswordUtil.hashPassword(password)) != 0;
            }
        }
    }




  /*
    private final UserToElasticsearch userToElasticsearch;







	*//**
	 * 获取mysql的所有信息增加到es
	 *//*
	public void mysqlToEs()
    {
		//图书表
        List<BookDTO> bookList = userMapper.getAllBook();
        for (BookDTO bookDTO : bookList)
        {
	        rabbitTemplate.convertAndSend("zijinyunyou.direct", "insert", new MySQLInsertEsByRabbitMQ(bookDTO.getId(), bookDTO, "book"));
        }
        //图书通知表
		List<NoticeDTO> libraryNotice = userMapper.getAllLibraryNotice();
        for (NoticeDTO noticeDTO : libraryNotice)
        {
	        rabbitTemplate.convertAndSend("zijinyunyou.direct", "insert", new MySQLInsertEsByRabbitMQ(noticeDTO.getId(), noticeDTO, "library_notice"));
        }
		//宿舍通知表
		List<NoticeDTO> dormitoryNotice = userMapper.getAllDormitoryNotice();
        for (NoticeDTO noticeDTO : dormitoryNotice)
        {
	        rabbitTemplate.convertAndSend("zijinyunyou.direct", "insert", new MySQLInsertEsByRabbitMQ(noticeDTO.getId(), noticeDTO, "dormitory_notice"));
        }
	    //借阅表
	    List<BorrowingDTO> borrowings = userMapper.getAllBorrowing();
		for (BorrowingDTO borrowingDTO : borrowings)
		{
			rabbitTemplate.convertAndSend("zijinyunyou.direct", "insert", new MySQLInsertEsByRabbitMQ(borrowingDTO.getId(), borrowingDTO, "borrowing"));
		}
	    //用户表
		List<UserDTO> users = userMapper.getAllUser();
	    for (UserDTO userDTO : users)
	    {
		    rabbitTemplate.convertAndSend("zijinyunyou.direct", "insert", new MySQLInsertEsByRabbitMQ(userDTO.getId(), userDTO, "user"));
	    }
    }




    *//**
     * 根据ID获取用户基本信息
     *
     * @param id 用户ID
     * @return 用户基本信息对象
     *//*
    public UserVO getBasicInfo(int id)
    {
        return userMapper.getBasicInfo(id);
    }


    *//**
     * 获取指定用户ID对应的用户头像图片。
     *
     * @param id 用户的唯一标识符
     * @return 返回与用户ID关联的用户头像图片对象
     *//*
    public Avatar getAvatarById(int id)
    {
        return userMapper.getAvatarById(id);
    }
	
	
	*//**
	 * 根据ID获取用户姓名
	 * @param id 用户id
	 * @return 获取用户头像和昵称对象
	 *//*
	public String getNameById(int id)
	{
		return userMapper.getNameById(id);
	}


    *//**
     * 更新用户头像信息。
     *
     * @param userId 用户唯一标识符
     * @param avatarImage 新的头像文件，以MultipartFile形式上传
     * @return 操作结果描述，成功时返回"更新成功"
     * @throws IOException 如果读取文件字节过程中发生I/O错误
     *//*
    public String updateAvatar(int userId, MultipartFile avatarImage) throws IOException
    {
        if (userMapper.updateAvatar(userId, avatarImage.getBytes()) != 0)
        {
	        return "更新成功";
        }
        else
        {
	        return "更新失败";
        }
    }


    *//**
     * 导出用户信息为Excel文件
     *
     * @param id 用户ID，用于获取特定用户的信息
     * @return Workbook 生成的包含用户信息的Excel工作簿
     *//*
    public Workbook exportUserInfo(int id)
    {
        //设置标题头
        String[] headers = {"学号", "姓名", "出生日期", "性别", "邮箱", "手机", "学院", "专业", "宿舍", "家庭住址"};
        //设置数据
        List<List<String>> data = new ArrayList<>();
        //添加一条数据
        UserVO userVO = userMapper.getBasicInfo(id);
        List<String> info = new ArrayList<>();
        info.add(userVO.getAccount());
        info.add(userVO.getName());
        info.add(userVO.getBirthday().toString());
        info.add(userVO.getSex());
        info.add(userVO.getEmail());
        info.add(userVO.getPhone());
        info.add(userVO.getCollegeName());
        info.add(userVO.getMajorName());
        info.add(userVO.getDormitoryNumber());
        info.add(userVO.getAddress());
        data.add(info);
        //返回工作簿
        return ExcelUtil.createExcelFile("用户信息", headers, data);
    }*/

}
